package com.geotmt.billingcenter.common.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Enumeration;

/**
 * @Description IP地址
 * @Author      yanghanwei
 * @Mail        yanghanwei@geotmt.com
 * @Date        2019/4/12 16:57
 * @Version     v1
 **/
public class IpUtils {

	private static Logger logger = LoggerFactory.getLogger(IpUtils.class);

	/**
	 * 获取IP地址
	 * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
	 * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
    	String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
        	logger.error("IpUtils ERROR ", e);
        }
        
        //使用代理，则获取第一个IP地址
        if(StringUtils.isEmpty(ip) && ip.length() > 15) {
			if(ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
        
        return ip;
    }

    public static String getCurrentIp2(){
        InetAddress address = null;
        String hostAddress = "";
        try {
            address = InetAddress.getLocalHost();
            hostAddress = address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return hostAddress;
    }

    public static String getCurrentIp1() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
                Enumeration<InetAddress> nias = ni.getInetAddresses();
                while (nias.hasMoreElements()) {
                    InetAddress ia = (InetAddress) nias.nextElement();
                    if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                        return StringUtils.substring(ia.toString(),1);
                    }
                }
            }
        } catch (SocketException e) {
        }
        return null;
    }

    /**
     * 通过执行ip a | grep xxx.xx.xx.xxx 判断当前是否为 xxx.xx.xx.xxx 服务器
     * 如果是则返回 xxx.xx.xx.xxx,如果不是则返回 "empty"
     * @return
     */
    public static String getCurrentIp(String masterIp){
        String [] cmd={"/bin/sh","-c","ip a |grep " + masterIp};
        Process proc = null;
        InputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            proc = Runtime.getRuntime().exec(cmd);
            if(null!=proc) {
                fis = proc.getInputStream();
                try (InputStreamReader inputStreamReader = isr = new InputStreamReader(fis)) {
                }
                br = new BufferedReader(isr);
                String line = "";
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    return masterIp;
                }
            }else{
                logger.error("execute command 'ip a|grep {}' error,please check",masterIp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(null != br){
                    br.close();
                }
                if(null != isr){
                    isr.close();
                }
                if(null != fis){
                    fis.close();
                }
                if(null != proc){
                    proc.destroy();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return "empty";
    }


    /**
     * 判断IP是否与当前server一致
     * @param masterIp
     * @return
     */
    public static boolean isSame(String masterIp){
        String currentIp1 = IpUtils.getCurrentIp1();
        logger.info("当前服务器IP为：{}",currentIp1);
        if(!StringUtils.isEmpty(masterIp) && masterIp.equals(currentIp1)){
            return true;
        }
        return false;
    }
}
